// src/services/userService.ts
import { AigcTask } from 'server/entity/AigcTask';
import { AppDataSource } from '../db';
import { SysUser } from '../entity/SysUser';
import { AppTestDataSource } from 'server/testdb';
import { TaskScoring } from 'server/entity/TaskScoring';

export async function searchUsers(): Promise<SysUser[]> {
    const userRepository = AppDataSource.getRepository(SysUser);
    const usersWithOrders = await userRepository.createQueryBuilder('user')
    .innerJoin(AigcTask, 'task', 'task.userId = user.id')
    .select('user.id')
    .distinct(true)
    .where('user.test_user != 1')
    .getMany();
    return usersWithOrders;
}

export async function searchUsersGoodRate(): Promise<any> {
    const userRepository = AppTestDataSource.getRepository(TaskScoring);
    const averageScores = await userRepository
      .createQueryBuilder('task_scoring')
      .select('task_scoring.task_id', 'task_id')
      .addSelect('AVG(task_scoring.major_score)', 'average_score')
      .groupBy('task_scoring.task_id')
      .getRawMany();
    const allLen = averageScores.length;
    const goodProductLen = averageScores.filter(item => item.average_score >= 39).length;
    const goodProductRate = allLen > 0 ? Math.ceil((goodProductLen / allLen) * 100) || 0 : 0;
    return { goodProductRate, productLen: allLen };
}

export async function searchUsersTask(): Promise<any> {
  const userRepository = AppDataSource.getRepository(AigcTask);
  const averageScores = await userRepository.createQueryBuilder('task')
    .innerJoin(SysUser, 'user', 'task.userId = user.id AND user.test_user != 1')
    .where('task.mark IS NULL OR task.mark NOT IN (:...marks)', { marks: ['BATCH_ORDER', 'TRAINING_SET'] })
    .select('task.*')
    .getRawMany();
  const allLen = averageScores.length;
  return { aigcTaskCount: allLen };
}